<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="500px" append-to-body custom-class="import-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称" :disabled="userNameDisabled" />
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入用户名称" maxlength="11" v-input.int @input="checkUserMobile" />
          <span>手机号作为用户的登录账号，创建后密码默认123456</span>
        </el-form-item>
<!--        <el-form-item label="角色" prop="roleId">-->
<!--          <el-select v-model="form.roleId" placeholder="请选择">-->
<!--            <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="form.roleIds" placeholder="请选择" filterable multiple>
            <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addUserBusiness, updateUserBusiness, checkUserMobile } from "@/api/sys-enterprise/account";
import { roleListByManage } from "@/api/sys-role/enterprise-role"
import { debounce } from "@/utils";
export default {
  props: {
    title: {
      default: "新增机构信息",
    },
    value: {
      default: false,
    },
    data: {
      default: undefined,
    },
  },
  data() {
    return {
      visible: false,
      form: {},
      rules: {
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        roleId: [
          { required: true, message: '角色不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ],
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      //列表
      list: [],
      //角色列表
      roleList: [],
      //用户名称禁止输入
      userNameDisabled: false
    };
  },
  watch: {
    value(newVal, oldVal) {
      if (newVal) {
        this.init();
      }
      this.visible = newVal; // 监测value的变化，并赋值。
    },
    visible(val) {
      this.$emit("input", val); // 此处监测visible目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    },
  },
  methods: {
    init() {
      this.reset()
      this.getRoleList()
    },
    reset() {
      // this.dateRange = [];
      this.userNameDisabled = false
      this.form = {
        userName: '',
        phonenumber: undefined,
        roleId: undefined,
        roleIds: [],
        roles: [],
        status: '0',
        tenantId: undefined,
        oldTenantId: undefined
      }
      this.resetForm("form");
      for (const key in this.data) {
        if (Object.hasOwnProperty.call(this.data, key)) {
          this.form[key] = this.data[key];
        }
      }

      this.form.roleIds = this.form.roles.map(item => item.roleId)
      this.form['oldTenantId'] = this.data['tenantId'];
    },
    //获取角色列表
    getRoleList() {
      roleListByManage().then(response => {
        this.roleList = response.data.map(item => {
          return {
            value: item.roleId,
            label: item.roleName
          }
        })
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.userId) {
            updateUserBusiness(this.form).then(response => {
              if (response.code === 200) {
                this.$emit("success");
                this.$message.success(response.msg);
                this.visible = false;
              } else {
                this.$message.error(response.msg);
              }
            })
          } else {
            addUserBusiness(this.form).then(response => {
              if (response.code === 200) {
                this.$emit("success");
                this.$message.success(response.msg);
                this.visible = false;
              } else {
                this.$message.error(response.msg);
              }
            })
          }
        }
      })
    },
    cancel() {
      this.reset();
      this.visible = false;
    },
    //检查用户手机号是否存在
    checkUserMobile: debounce(function () {
      let phoneNumber = this.form.phonenumber
      var regex = /^[1][3-9]\d{9}$/;
      if (phoneNumber.length < 11) {
        if (this.userNameDisabled) {
          this.form.userName = ''
        }
        this.userNameDisabled = false
        return
      }
      if (!regex.test(phoneNumber)) {
        this.$message.error('请输入正确的手机号码')
        return
      }
      checkUserMobile(phoneNumber).then(res => {
        if (res.code == 200) {
          if (res.state) {
            this.form.userName = res.userName
            this.userNameDisabled = true
          }
          // else {
          //   this.userNameDisabled = false
          //   this.form.userName = ''
          // }
        } else {
          this.$message.error('异常')
        }
      }).catch(err => {
        this.$message.error('网络异常')
      })
    }, 500)
  },
};
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/dialog.scss";
</style>
